#include "BaseType.h"
#include "Tracer.h"
#include "Socket.h"
#include "Thread.h"

using namespace libemb;

#define SERVER_IP	"127.0.0.1" /* 定义服务器地址 */
#define SERVER_PORT	(8000)		/* 定义服务器端口 */
#define CLIENT_PORT (7999)

class MyTcpServer : public TcpServer{
public:
    void onNewConnection(std::unique_ptr<TcpSocket> client)
    {
    	/* 只允许处理一个连接,直接在此函数对connSocket进行处理 */
        while(client)
        {
            char buf[64]={0};
            sint32 rc=client->recvData(buf, sizeof(buf)-1,500000);
            if (rc>0)
            {
                TRACE_YELLOW("tcp server recv:[%s]\n",buf);
                char sbuf[]="hello, i am server!";
                client->writeData(sbuf,sizeof(sbuf));
				TRACE_YELLOW("tcp server send:[%s]\n",sbuf);
				Thread::msleep(1000);
				/* 回复客户端后停止服务 */
				stopServer();
				break;
            }
            else if (rc<0)/* 接收超时 */
            {
                continue;
            }
            else/* 客户端已断开连接 */
            {
                break;
            }
			
        }
    }   
};

void testTcp(void)
{
	TRACE_INFO("tcp test start >>>>>>\n");
	/* 创建一个线程给服务器,模拟服务器进程 */
	Thread serThread;
    MyTcpServer server;
    server.startServer(SERVER_IP,SERVER_PORT);

	/* 启动服务线程 */
	serThread.start(server);
	Thread::msleep(1000);
    TRACE_REL("tcp server ready.\n");
	
    /* 客户端在当前进程 */
	TcpSocket client;
	if(!client.open("",CLIENT_PORT))
	{
		TRACE_ERR("tcp client open error!\n");
	}
	
	if(!client.setConnection(SERVER_IP,SERVER_PORT))
	{
		TRACE_ERR("connect tcp server error!\n");
	}

	/* 发送消息给服务器 */
	char sendBuf[]="hello, i am client!";
	if(client.sendData(sendBuf, sizeof(sendBuf),-1)>0)
	{
		TRACE_CYAN("tcp client send: %s\n",sendBuf);
	}
	else
	{
		TRACE_ERR("tcp client send error!\n");
	}

	/* 读取服务端回复消息 */
    char buf[64]={0};
    int rc=client.recvData(buf, sizeof(buf), 10000000);
    if (rc>0)
    {
        TRACE_CYAN("tcp client recv:[%s]\n",buf);
    }
	else
	{
		TRACE_ERR("tcp client recv error!\n");
	}
	if (!serThread.stop(1000))
    {
    	serThread.forceQuit();
	}
	TRACE_INFO("tcp test finished <<<<<<\n");
}
